package com.geovis.emergency.spd.biz.zwdd.handler;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.xxpt.gateway.shared.api.request.OapiMoziEmployeeGetEmployeeByCodeRequest;
import com.alibaba.xxpt.gateway.shared.api.response.OapiMoziEmployeeGetEmployeeByCodeResponse;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.IntelligentGetClient;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.geovis.common.auth.util.AuthUtil;
import com.geovis.common.core.constant.CommonConstants;
import com.geovis.emergency.spd.biz.system.service.ISystemDeptService;
import com.geovis.emergency.spd.biz.system.service.ISystemUserService;
import com.geovis.emergency.spd.biz.zwdd.props.ZwddProperties;
import com.geovis.emergency.spd.entity.system.entity.SystemUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class ZwddEventCallbackHandler {

    private final ISystemUserService systemUserService;

    private final ISystemDeptService systemDeptService;

    private final ExecutableClient executableClient;

    private final ZwddProperties zwddProperties;

    /**
     * 新增或修改组织
     *
     * @param content
     */
    public void deptAddUpdate(String content) {

    }

    /**
     * 删除组织
     *
     * @param content
     */
    public void deptRemove(String content) {

    }

    /**
     * 组织变更父组织
     *
     * @param content
     */
    public void deptParentChange(String content) {

    }

    /**
     * 删除用户
     *
     * @param content
     */
    // {"accountId":827362,"userInfo":[{"accountId":827362,"employeeCode":"GE_0456cecf151149818b13012d2a19c670"}],"employeeCodes":["GE_0456cecf151149818b13012d2a19c670"],"tenantId":12709,"tag":"EMPLOYEE_LEAVE","operator":"760524"}
    public void employeeRemove(String content) {

    }

    /**
     * 员工新增和修改
     *
     * @param content
     */
    // 新增 {"accountId":827362,"userInfo":[{"accountId":827362,"employeeCode":"GE_0456cecf151149818b13012d2a19c670"}],"employeeChangeType":"create","employeeCodes":["GE_0456cecf151149818b13012d2a19c670"],"employeeChangeMoMap":{"GE_0456cecf151149818b13012d2a19c670":{"currStatus":"A"}},"tenantId":12709,"tag":"EMPLOYEE_ADD_UPDATE"}
    // 修改  {"accountId":821446,"userInfo":[{"accountId":821446,"employeeCode":"GE_c7a3aff3ff9d484fb1fd300b75a9ff63"}],"employeeChangeType":"update","employeeCodes":["GE_c7a3aff3ff9d484fb1fd300b75a9ff63"],"employeeChangeMoMap":{"GE_c7a3aff3ff9d484fb1fd300b75a9ff63":{"currEmployee":{"employeeName":"曾德实","creator":"736326","gmtModified":1651140694000,"modifier":"760524","id":50187887,"gmtCreate":1647848275000,"govaffairsBaseProperties":{"govEmpCellPhoneNo":"UEsAAgECAAEAAAANAAgAAQAAAAAAADGlMAAAAAAAAACV7k8a3Iimrg+twSo4rfz6u7MaE6qTn75FuEZOSpuhKwQV1tnTF/9SGomd1oRa+1qJG5JY7CDtlzcdvjpE1j/qQdFlG5YfDKW3UAAeYUukfgAAAAAAAAAAAAAAAIYfm1xDSVACAgEAAAAAAAAAAAAAQdFlG5YfDKW3UAAeYUukfr6sljMVRgB7Ed/IkcMpdzAwx39p7Md2Pos7ET4H7yfVL8C8K3hyc5f1QFrB874kxIYIB1PmbJUmUOoVnfsQRic=","govEmpCellPhoneAreaCode":"86","govEmpJobLevel":{"code":"ZHI_JI_QI_TA","name":"其他"},"extProps":{},"govEmpBudgetedPost":{"code":"BIAN_ZHI_QI_TA","name":"其他"},"govEmpGender":{"code":"9","name":"未说明的性别"}},"employeeCode":"GE_c7a3aff3ff9d484fb1fd300b75a9ff63","status":"A"},"prevEmployee":{"employeeName":"曾德实hero","creator":"736326","gmtModified":1651136995000,"modifier":"760524","id":50187887,"gmtCreate":1647848275000,"govaffairsBaseProperties":{"govEmpCellPhoneNo":"UEsAAgECAAEAAAANAAgAAQAAAAAAADGlMAAAAAAAAACV7k8a3Iimrg+twSo4rfz6u7MaE6qTn75FuEZOSpuhKwQV1tnTF/9SGomd1oRa+1qJG5JY7CDtlzcdvjpE1j/qQdFlG5YfDKW3UAAeYUukfgAAAAAAAAAAAAAAAIYfm1xDSVACAgEAAAAAAAAAAAAAQdFlG5YfDKW3UAAeYUukfr6sljMVRgB7Ed/IkcMpdzAwx39p7Md2Pos7ET4H7yfVL8C8K3hyc5f1QFrB874kxIYIB1PmbJUmUOoVnfsQRic=","govEmpCellPhoneAreaCode":"86","govEmpJobLevel":{"code":"ZHI_JI_QI_TA","name":"其他"},"extProps":{},"govEmpBudgetedPost":{"code":"BIAN_ZHI_QI_TA","name":"其他"},"govEmpGender":{"code":"9","name":"未说明的性别"}},"employeeCode":"GE_c7a3aff3ff9d484fb1fd300b75a9ff63","status":"A"},"prevStatus":"A","currStatus":"A","currEmployeeName":"曾德实","prevEmployeeName":"曾德实hero"}},"tenantId":12709,"tag":"EMPLOYEE_ADD_UPDATE"}
    public void employeeAddUpdate(String content) {
        JSONObject contentJsonObject = JSONUtil.parseObj(content);
        if (ObjectUtil.isEmpty(contentJsonObject)) {
            return;
        }
        String employeeChangeType = contentJsonObject.getStr("employeeChangeType");
        // 新增
        if (StrUtil.equals("create", employeeChangeType)) {
            JSONObject userInfo = contentJsonObject.get("userInfo", JSONObject.class);
            String employeeCode = userInfo.getStr("employeeCode");
            SystemUser systemUser = new SystemUser();
            systemUser.setUserName(userInfo.getStr("accountId")).setId(employeeCode);
            // 查询用户信息
            JSONObject queryUserInfo = getEmployeeByCode(employeeCode);
            systemUser.setNickName(queryUserInfo.getStr("employeeName"))
                    .setRealName(systemUser.getNickName())
                    .setUserPassword(AuthUtil.getDefaultPassword())
                    .setDataStatus(CommonConstants.YES);
            systemUserService.saveOrUpdate(systemUser);
        } else {
            // 修改
            List<String> $employeeCodeList = contentJsonObject.getBeanList("employeeCodes", String.class);
            List<SystemUser> systemUserList = systemUserService.listByIds($employeeCodeList);
            Map<String, SystemUser> systemUserMap = IterUtil.toMap(systemUserList, SystemUser::getId);
            JSONObject employeeChangeMoMap = contentJsonObject.get("employeeChangeMoMap", JSONObject.class);
            List<SystemUser> resultList = $employeeCodeList.stream().map(employeeCode -> {
                JSONObject employeeCodeObject = employeeChangeMoMap.get(employeeCode, JSONObject.class);
                JSONObject currEmployee = employeeCodeObject.get("currEmployee", JSONObject.class);
                SystemUser systemUser = systemUserMap.get(employeeCode);
                if (ObjectUtil.isEmpty(systemUser)) {
                    systemUser = new SystemUser();
                }
                systemUser.setUserName(contentJsonObject.get("accountId", String.class))
                        .setUserPassword(AuthUtil.getDefaultPassword())
                        .setNickName(currEmployee.get("employeeName", String.class))
                        .setRealName(currEmployee.get("employeeName", String.class))
                        .setDataStatus(StrUtil.equals(currEmployee.get("status", String.class), "A") ? CommonConstants.YES : CommonConstants.NO).setId(employeeCode);
                return systemUser;
            }).collect(Collectors.toList());
            systemUserService.saveOrUpdateBatch(resultList);
        }
    }

    /**
     * 组织关联员工
     *
     * @param content
     */
    // {"organizationCodes":["GO_5ba541f2d4cf40e48161ab7ace9381ae"],"employeeCodes":["GE_0456cecf151149818b13012d2a19c670"],"tenantId":12709,"tag":"ORGANIZATION_ATTACH_EMPLOYEE","infos":[{"principal":true,"accountId":827362,"organizationCode":"GO_5ba541f2d4cf40e48161ab7ace9381ae","tenantId":12709,"employeeCode":"GE_0456cecf151149818b13012d2a19c670"}]}
    public void deptAttachEmployee(String content) {
        JSONObject contentJsonObject = JSONUtil.parseObj(content);
        if (ObjectUtil.isEmpty(contentJsonObject)) {
            return;
        }
        JSONObject infos = contentJsonObject.getJSONObject("infos");
        systemUserService.update(Wrappers.lambdaUpdate(SystemUser.class)
                .set(SystemUser::getDeptId, infos.getStr("organizationCode"))
                .eq(SystemUser::getId, infos.getStr("employeeCode"))
        );
    }

    /**
     * 组织取消关联员工
     *
     * @param content
     */
    // {"organizationCodes":["GO_5ba541f2d4cf40e48161ab7ace9381ae"],"employeeCodes":["GE_0456cecf151149818b13012d2a19c670"],"tenantId":12709,"tag":"ORGANIZATION_DETACH_EMPLOYEE","infos":[{"principal":true,"accountId":827362,"organizationCode":"GO_5ba541f2d4cf40e48161ab7ace9381ae","tenantId":12709,"employeeCode":"GE_0456cecf151149818b13012d2a19c670"}]}
    public void deptDetachEmployee(String content) {
        JSONObject contentJsonObject = JSONUtil.parseObj(content);
        if (ObjectUtil.isEmpty(contentJsonObject)) {
            return;
        }
        JSONObject infos = contentJsonObject.getJSONObject("infos");
        systemUserService.update(Wrappers.lambdaUpdate(SystemUser.class)
                .set(SystemUser::getDeptId, null)
                .eq(SystemUser::getId, infos.getStr("employeeCode"))
        );
    }

    public JSONObject getEmployeeByCode(String code) {
        // 查询用户详情
        OapiMoziEmployeeGetEmployeeByCodeRequest request = new OapiMoziEmployeeGetEmployeeByCodeRequest();
        IntelligentGetClient intelligentGetClient = executableClient.newIntelligentGetClient(request.getApiUrl());
        OapiMoziEmployeeGetEmployeeByCodeRequest oapiMoziEmployeeGetEmployeeByCodeRequest = new OapiMoziEmployeeGetEmployeeByCodeRequest();
        oapiMoziEmployeeGetEmployeeByCodeRequest.setEmployeeCode(code);
        oapiMoziEmployeeGetEmployeeByCodeRequest.setTenantId(zwddProperties.getTenantId());
        //获取结果
        OapiMoziEmployeeGetEmployeeByCodeResponse apiResult = intelligentGetClient.get(oapiMoziEmployeeGetEmployeeByCodeRequest);
        return JSONUtil.toBean(apiResult.getContent().getData(), JSONObject.class);
    }

}
